// 面试单例懒汉线程安全
#include <iostream>
using namespace std;
//懒汉线程不安全
template <typename T>
class Singleton_unsafe {
 public:
  static T& getInstance() {
    if (!value_) {
      value_ = new T();
    }
    return *value_;
  }

 private:
  Singleton_unsafe();
  ~Singleton_unsafe();
  static T* value_;
};
template <typename T>
T* Singleton_unsafe<T>::value_ = NULL;
//懒汉线程安全
template <typename T>
class Singleton_safe {
 public:
  static T& getInstance() {
    if (!value_) {
      value_ = new T();
    }
    return *value_;
  }

 private:
  class CGarbo {
   public:
    CGarbo() { printf("CGarbo construct\n"); }
    ~CGarbo() {
      printf("CGarbo destruct\n");
      if (Singleton_safe::value_) {
        delete Singleton_safe::value_;
      }
    }
  };
  static CGarbo Garbo;
  Singleton_safe();
  ~Singleton_safe();
  static T* value_;
};
template <typename T>
T* Singleton_safe<T>::value_ = nullptr;
//饿汉线程安全
class Log {
 public:
  static Log* GetInstance() {
    static Log oLog;
    return &oLog;
  }
  void Output(string strLog) {
    cout << strLog << "," << (*m_pInt) << "." << endl;
  }

 private:
  Log() : m_pInt(new int(3)) {}
  ~Log() {
    cout << "~Log" << endl;
    delete m_pInt;
    m_pInt = nullptr;
  }
  int* m_pInt;
};
class Context {
 public:
  static Context* GetInstance() {
    static Context oContext;
    return &oContext;
  }
  ~Context() { Log::GetInstance()->Output(__FUNCTION__); }
  void fun() { Log::GetInstance()->Output(__FUNCTION__); }

 private:
  Context() {}
  Context(const Context& context);
};
int main_sing() {
  Context::GetInstance()->fun();
  auto n = Singleton_safe<int>::getInstance();
  printf("%d\n", n);
  return 0;
}
